const ol = require("ol3");
const Tile = require("../Tile");
const React = require("react");
const StripeData = require("../../../data/data");

var styles = [
    /* We are using two different styles for the polygons:
     *  - The first style is for the polygons themselves.
     *  - The second style is to draw the vertices of the polygons.
     *    In a custom `geometry` function the vertices of a polygon are
     *    returned as `MultiPoint` geometry, which will be used to render
     *    the style.
     */
    new ol.style.Style({
        stroke: new ol.style.Stroke({
            color: 'blue',
            width: 3
        }),
        fill: new ol.style.Fill({
            color: 'rgba(0, 0, 255, 0.1)'
        })
    })
];

const InitPage = React.createClass({

    renderPolygons(map){
        var features = StripeData.map(function(item){
            var wkt = item.wkt;

            var format = new ol.format.WKT();

            return format.readFeature(wkt, {
                dataProjection: 'EPSG:4326',
                featureProjection: 'EPSG:3857'
            });
        });

        var vectorLayer = new ol.layer.Vector({
            source: new ol.source.Vector({
                features: features
            }),
            style: styles
        });

        map.addLayer(vectorLayer);

        return features;
    },

    renderImageLayer(features, map){
        var imageOptions = features.map(function(feature, index){
            var poly = feature.getGeometry();
            var item = StripeData[index];
            return {
                url: "../data/"+item.name+"/"+item.fileURL,
                imageExtent: poly.getExtent(),
                targetPolygon: poly
            }
        });

        var imageLayer = new ol.layer.CollectionLayer({
            projection: 'EPSG:3857',
            map: map,
            direction: "right_up"
        });

        imageLayer.addImages(imageOptions);

        imageLayer.setOpacity(0.5);
    },

    componentDidMount(){
        var map = new ol.Map({
            target: 'map',
            layers: [
                new ol.layer.Tile({
                    source: new ol.source.OSM()
                })
            ],
            view: new ol.View({
                center: ol.proj.fromLonLat([116,41]),
                zoom: 4
            })
        });

        var features = this.renderPolygons(map);
        this.renderImageLayer(features, map);
    },

    render(){
        return (
            <div className="container">
                <Tile header="旋转">
                    <div id="map">

                    </div>
                </Tile>
            </div>
        );
    }
});

module.exports = InitPage;